<template>
  <a-modal
    v-model:visible="modalVisible"
    :title="qcodeTitle"
    unmount-on-close
    :mask-closable="false"
    width="65vw"
    :footer="qcodeTitle != '收款码' ? true : false"
    @close="onClose"
    @before-open="onBeforeOpen"
  >
    <div v-if="qcodeTitle != '收款码'" class="mb-2.5 qcode-alert">
      <icon-info-circle-fill class="mx-2.5" size="16" />
      当前费用关联了合并确认的三方支付账单，请确认是否取消账单下所有费用的收付款？
    </div>

    <a-descriptions :size="'medium'" :align="{ label: 'right' }">
      <a-descriptions-item label="账单号">{{ qcodeDetails?.billCode }}</a-descriptions-item>
      <a-descriptions-item label="外部账单号">{{ qcodeDetails?.outBillCode }}</a-descriptions-item>
    </a-descriptions>

    <a-divider v-if="qcodeTitle == '收款码'" />

    <table-index @loadData="loadData" :table="table">
      <template #costDetails="{ record }">
        <div v-for="(item, index) in record.feeList" :key="item.id">
          <span
            class="td"
            style="position: relative; padding: 0"
            :class="{ 'padding-top-0': index == 0, 'border-none padding-bottom-0': index == record.feeList.length - 1 }"
            :style="{
              height: '42px',
              'line-height': '42px',
            }"
          >
            {{ item.feeName }}: {{ item.feeActiveAmount }}
          </span>
        </div>
      </template>
    </table-index>

    <a-divider v-if="qcodeTitle == '收款码'" />

    <div class="qcode-box" v-if="qcodeTitle == '收款码'">
      <template v-if="qcodeDetails?.scanQrCode && !Rejected && !Fulfilled">
        <div class="qcode-title mb-10">
          提示：请于 <span style="color: #3072f6">{{ qcodeDetails?.expireTime }}</span> 前完成账单的支付，否则账单会自动取消
        </div>
        <div class="qrcode">
          <div class="mb-2.5">嘉联聚合支付</div>
          <qrcode-vue :value="qcodeDetails?.scanQrCode" :size="200" level="H" class="mb-5" />
          <div>
            <img src="~@/assets/yunshanfu.png" alt="云闪付" class="w-12 mr-12" />
            <img src="~@/assets/alipay.png" alt="支付宝" class="w-12 mr-12" />
            <img src="~@/assets/wechat.png" alt="微信" class="w-12" />
          </div>
        </div>
      </template>

      <template v-else-if="Rejected || Fulfilled">
        <div v-if="Rejected" class="flex flex-col">
          <img src="~@/assets/pay-error.png" class="w-12" />
          支付失败
        </div>
        <div v-if="Fulfilled" class="flex flex-col">
          <img src="~@/assets/pay-success.png" class="w-12" />
          支付成功
        </div>
        <div class="pay-result">
          倒计时 <span style="color: #3072f6">{{ count }}s</span> 后自动关闭弹窗，并刷新数据
        </div>
      </template>
    </div>

    <template #footer v-if="qcodeTitle != '收款码'">
      <a-button type="secondary" @click="onCancel">关闭</a-button>
      <a-button type="primary" @click="onConfirm" :loading="qcodeCfLoading">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import QrcodeVue from 'qrcode.vue'

  import { computed, ref } from 'vue'
  import { useTable } from '@/hooks/table'
  import { getPayCode, getPayStatus, queryScanCode } from '@/api/common'
  import { Message } from '@arco-design/web-vue'

  const props = defineProps({
    details: {
      type: Object,
      default: () => {},
    },
    visible: {
      type: Boolean,
      default: false,
    },
    qcodeTitle: {
      type: String,
      default: '收款码',
    },
    qcodeCfLoading: {
      type: Boolean,
      default: false,
    },
    from: {
      type: String,
      default: '',
    },
  })

  const TIME_COUNT = 3
  const count = ref(TIME_COUNT)
  let downTimer: any = null
  const countDown = () => {
    if (!downTimer) {
      downTimer = setInterval(() => {
        count.value--
        if (count.value === 0) {
          clearInterval(downTimer)
          downTimer = null
          modalVisible.value = false
        }
      }, 1000)
    }
  }

  const emits = defineEmits(['update:visible', 'close', 'confirm'])

  const modalVisible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })

  const table = useTable({
    pagination: false,
    columns: [
      { title: '费用明细', slotName: 'costDetails', fixed: 'left' },
      { title: '支付状态', dataIndex: 'payStatusName' },
      { title: '账单金额', dataIndex: 'totalAmount', unit: '元' },
      { title: '客户名称', dataIndex: 'customerName' },
      { title: '费用备注', dataIndex: 'remark' },
      { title: '操作人', dataIndex: 'createUserName' },
      { title: '账单生成时间', dataIndex: 'createTime', fixed: 'right' },
    ],
  })

  const payStatus = (orderSerialNo: string) => {
    return new Promise((resolve) => {
      getPayStatus({ orderSerialNo }).then((res: any) => {
        console.log('getPayStatus', res)

        resolve(res.result)
      })
    })
  }

  let timer: any = null
  const Rejected = ref(false) // 支付失败
  const Fulfilled = ref(false) // 支付成功
  const DELAY = 3000
  // 通过轮询获取支付状态
  const pollingPayStatus = (orderSerialNo: string, delay = DELAY) => {
    payStatus(orderSerialNo).then((result: any) => {
      // 支付成功
      if (result.resultCode == 200) {
        clearTimeout(timer)
        timer = null
        Fulfilled.value = true
        loadData(true)
        countDown()
      } else if (result.resultCode == 300) {
        clearTimeout(timer)
        timer = null
        Rejected.value = true
        loadData(true)
        countDown()
      } else {
        timer = setTimeout(() => {
          pollingPayStatus(orderSerialNo, delay)
        }, delay)
      }
    })
  }

  // 从确认收款按钮进入
  const COMFIRMPAY_ARRAY = ['orderConfirmFee', 'violationConfirmFee']
  // 从收款码/取消收款按钮进入
  const PAYCODE_OR_UNPAYCODE_ARRAY = [
    'shortOrderQRCode',
    'shortOrderQRCodeCancel',
    'longOrderQRCode',
    'longOrderQRCodeCancel',
    'carViolationQRCode',
    'carViolationCancel',
    'costShortOrderQRCode',
    'costShortOrderQRCodeCancel',
    'costLongOrderQRCode',
    'costLongOrderQRCodeCancel',
    'costCarViolationQRCode',
    'costCarViolationCancel',
  ]

  const qcodeDetails = ref<any>({})
  const loadData = (is_start_get_pay_status = false) => {
    table.tableLoading = true

    if (COMFIRMPAY_ARRAY.includes(props.from)) {
      getPayCode({ id: props.details.qrcodeId })
        .then((res: any) => {
          console.log('getPayCode', res.result)

          const { result } = res
          qcodeDetails.value = result
          table.dataList = [result]

          if (result?.scanQrCode && props.qcodeTitle == '收款码' && !is_start_get_pay_status) {
            pollingPayStatus(result.billCode)
          }
        })
        .finally(() => {
          table.tableLoading = false
        })
    } else if (PAYCODE_OR_UNPAYCODE_ARRAY.includes(props.from)) {
      queryScanCode({ bizType: props.details?.bizType, feeId: props.details?.id, refId: props.details.refId })
        .then((res: any) => {
          console.log('getPayQRCode', res)

          const { result } = res
          qcodeDetails.value = result
          table.dataList = [result]

          if (result?.scanQrCode && props.qcodeTitle == '收款码' && !is_start_get_pay_status) {
            pollingPayStatus(result.billCode)
          } else {
            payStatus(result.billCode).then((result: any) => {
              console.log('取消 getPayStatus', result)

              if (result.resultCode == 200 || result.resultCode == 300) {
                if (result.resultCode == 200) {
                  Message.success(result.msg)
                } else if (result.resultCode == 300) {
                  Message.error(result.msg)
                }

                modalVisible.value = false
              }
            })
          }
        })
        .finally(() => {
          table.tableLoading = false
        })
    }
  }

  const onBeforeOpen = () => {
    loadData()
  }

  const onConfirm = () => {
    emits('confirm', qcodeDetails.value)
  }

  const onCancel = () => {
    modalVisible.value = false
  }

  const onClose = () => {
    console.log('onClose')

    count.value = TIME_COUNT
    Rejected.value = false
    Fulfilled.value = false
    clearTimeout(timer)
    timer = null
    clearInterval(downTimer)
    downTimer = null

    emits('close')
  }
</script>

<style lang="less" scoped>
  .pay-result {
    font-weight: 400;
    font-size: 12px;
    color: #8491a8;
  }
  .qcode-alert {
    display: flex;
    align-items: center;
    background-color: #ffc7c7;
    color: #ea0000;
    height: 40px;
  }

  .td {
    display: inline-block;
    width: 100%;
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
    padding: 10px 0;
    &::before {
      content: '';
      display: block;
      position: absolute;
      left: -16px;
      right: -16px;
      bottom: 0;
      height: 0.5px;
      background-color: #e5e6eb;
    }
  }
  .td-bottom {
    &::before {
      content: '';
      display: block;
      position: absolute;
      left: -16px;
      right: -16px;
      bottom: 0;
      height: 0.5px;
      background-color: #e5e6eb;
    }
  }
  .padding-top-0 {
    padding-top: 0;
  }
  .padding-bottom-0 {
    padding-bottom: 0;
  }
  .border-none {
    &::before {
      content: none !important;
    }
  }

  .qcode-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 14px;
    color: #1d2129;

    .qrcode {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-weight: 500;
      font-size: 18px;
    }
  }
</style>
